<?php

namespace Gaolei\YiiRBAC\models\search;

use Gaolei\YiiRBAC\models\Adminer;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use yii\db\ActiveRecord;

/**
 * User represents the model behind the search form about `admin\models\User`.
 */
class AdminerSearch extends Model
{
    public $id;
    public $username;
    public $realname;
    public $phone;
    public $state;

    /**
     * @inheritdoc
     */
    public function rules(): array
    {
        return [
            [['id', 'state',], 'integer'],
            [['username', 'realname', 'phone'], 'safe'],
        ];
    }

    /**
     * Creates data provider instance with search query applied
     * @param array $params
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        /** @var ActiveRecord $class */
        $class = Yii::$app->getUser()->identityClass ?: Adminer::class;
        $query = $class::find();
        $dataProvider = new ActiveDataProvider(['query' => $query]);
        $this->load($params);
        if (!$this->validate()) {
            $query->where('1=0');
            return $dataProvider;
        }
        $query->andFilterWhere([
            'id' => $this->id,
            'state' => $this->state,
            'phone' => $this->phone
        ]);
        $query->andFilterWhere(['like', 'username', $this->username])
            ->andFilterWhere(['like', 'realname', $this->realname]);
        return $dataProvider;
    }
}
